import react, { useEffect, useState } from "react";

import { Select, Button, Space, Divider } from "antd";
import { MinusCircleOutlined } from "@ant-design/icons";

const { Option } = Select;

const tagListAll = [
  {
    tagName: "标签一",
    tagKey: "1",
    key: "1",
    value: "1",
    selectList: ["二级标签1", "二级标签2"],
  },
  {
    tagName: "标签二",
    tagKey: "2",
    key: "2",
    value: "2",
    selectList: ["二级标签3", "二级标签4"],
  },
  {
    tagName: "标签三",
    tagKey: "3",
    key: "3",
    value: "3",
    selectList: ["二级标签5", "二级标签6"],
  },
];

const customEffectTag = [
  {
    tagName: "标签一",
    tagKey: "1",
    key: "1",
    value: "1",
    selectList: ["二级标签1", "二级标签2"],
  },
];

const target = [
  {
    tagName: "标签一",
    tagKey: "1",
    key: "1",
    value: "1",
    selectList: ["二级标签1", "二级标签2"],
  },
  {
    tagName: "标签三",
    tagKey: "3",
    key: "3",
    value: "3",
    selectList: ["二级标签5"],
  },
];

// eslint-disable-next-line import/no-anonymous-default-export
export default () => {
  // 全量标签
  const [tagAll, seTagAll] = useState([]);

  // 未生效标签
  const [noEffectTag, setNoEffectTag] = useState([]);

  // 生效标签
  const [effectTag, setEffectTag] = useState([]);

  // 列表主键生成
  const [primaryKey, setPrimaryKey] = useState("");

  // 是按钮状态
  const [buttonStatus, setButtonStatus] = useState("edit"); // 1 3 为不可编辑态  2为可编辑状态

  const GenNonDuplicateID = (randomLength) => {
    const key = Number(
      Math.random().toString().substr(3, randomLength) + Date.now()
    ).toString(36);
    if (key !== primaryKey) {
      return key;
    }
    setPrimaryKey(key);
    GenNonDuplicateID(randomLength);
  };

  const templateTags = {
    tagName: "",
    tagKey: "",
    key: "",
    primaryKey: GenNonDuplicateID(6),
    value: "",
    selectList: [],
  };

  // 处理全量标签select对应的配置
  const updateTagAllOptions = (list) => {
    return list?.map((item) => {
      return {
        ...item,
        label: item?.tagName,
        value: item?.tagKey,
        siblingOptions: item?.selectList.map((item) => {
          return {
            label: item,
            value: item,
          };
        }),
      };
    });
  };

  // 处理未生效标签或则已生效标签 select对应的配置
  // 不依赖于tagAll
  const updateEffectTagAll = (list, listALl) => {
    const findOptions = (key) => {
      return listALl
        .find((item) => item.tagKey === key)
        ?.selectList.map((cItem) => {
          return {
            lable: cItem,
            value: cItem,
          };
        });
    };
    return list.map((item) => {
      return {
        ...item,
        primaryKey: GenNonDuplicateID(6),
        siblingOptions: findOptions(item.tagKey),
      };
    });
  };

  // 依赖于tagAll 找对应配置
  const findSiblingOptions = (key) => {
    return tagAll.find((item) => item.tagKey === key)?.siblingOptions;
  };

  const firstSelectChange = (e, index) => {
    // 1. 更新自身节点的tabkey, key, label, tagName,
    // 2. 更新 sibling节点的options配置
    const memoList = noEffectTag.slice();

    memoList[index] = {
      ...memoList[index],
      key: e?.value,
      tagKey: e?.value,
      value: e?.value,
      label: e?.label,
      tagName: e?.label,
      siblingOptions: findSiblingOptions(e?.value),
    };

    setNoEffectTag(memoList);
  };

  const secondSelectChange = (e, index) => {
    // 1. 更新 selectList
    const memoList = noEffectTag.slice();

    memoList[index] = {
      ...memoList[index],
      selectList: e,
    };
    setNoEffectTag(memoList);
  };
  // 删除节点
  const deleteTagList = (index) => {
    // 单纯用primaryKey删除一个列表项目
    const memoList = noEffectTag
      .slice()
      .filter((item) => item?.primaryKey !== index);
    setNoEffectTag(memoList);
  };

  // 添加节点
  const addTagList = () => {
    const memoList = noEffectTag.slice();
    memoList.push(templateTags);
    setNoEffectTag(memoList);
  };

  const editHandle = () => {
    setButtonStatus("canEdit");
  };

  const confirmEdit = () => {
    // 此处是set的后端返回的状态。正常是edit
    setButtonStatus("edit");
  };

  console.log(tagAll, "tagAll");
  console.log(noEffectTag, "noEffectTag");

  useEffect(() => {
    seTagAll(updateTagAllOptions(tagListAll));
    setNoEffectTag(updateEffectTagAll(target, tagListAll));
    setEffectTag(customEffectTag);
  }, []);

  return (
    <div>
      {effectTag.map((item) => {
        return (
          <Space>
            <span>产品类型</span>
            <Select defaultValue={item.value} style={{ width: 120 }} disabled>
              {tagAll.map((cItem) => {
                return <Option value={cItem.value}>{cItem.label}</Option>;
              })}
            </Select>
            <span>产品属性</span>
            <Select
              defaultValue={item.selectList}
              style={{ width: 240 }}
              mode="multiple"
              disabled
            />
          </Space>
        );
      })}
      <Divider dashed />
      {noEffectTag.map((item, index) => {
        return (
          <div key={item.primaryKey} style={{ marginBottom: "20px" }}>
            <Space>
              <span>产品类型</span>
              <Select
                defaultValue={item.value}
                style={{ width: 120 }}
                labelInValue
                onChange={(e) => firstSelectChange(e, index)}
                disabled={buttonStatus !== "canEdit"}
              >
                {tagAll.map((cItem) => {
                  return <Option value={cItem.value}>{cItem.label}</Option>;
                })}
              </Select>
              <span>产品属性</span>
              <Select
                defaultValue={item.selectList}
                style={{ width: 240 }}
                mode="multiple"
                onChange={(e) => secondSelectChange(e, index)}
                disabled={buttonStatus !== "canEdit"}
              >
                {item?.siblingOptions?.map((cItem) => {
                  return <Option value={cItem.value}>{cItem.label}</Option>;
                })}
              </Select>
              {!effectTag.some((c) => c.tagKey === item.tagKey) &&
                buttonStatus === "canEdit" && (
                  <MinusCircleOutlined
                    onClick={() => deleteTagList(item?.primaryKey)}
                  />
                )}
            </Space>
          </div>
        );
      })}

      {buttonStatus === "canEdit" && (
        <Button
          type="dashed"
          style={{ marginTop: "20px" }}
          onClick={() => addTagList()}
        >
          add
        </Button>
      )}

      <div>
        {buttonStatus === "edit" && (
          <>
            <Button
              type="primary"
              style={{ marginRight: "20px" }}
              onClick={() => editHandle()}
            >
              编辑
            </Button>
            <Button type="primary">发起审批</Button>
          </>
        )}
        {buttonStatus === "审批中" && (
          <>
            <Button type="primary" style={{ marginRight: "20px" }}>
              审批链接
            </Button>
            <Button type="primary">撤销审批</Button>
          </>
        )}
        {/* 前端自定义状态 */}
        {buttonStatus === "canEdit" && (
          <>
            <Button
              type="primary"
              style={{ marginRight: "20px" }}
              onClick={() => confirmEdit()}
            >
              确定修改
            </Button>
            <Button type="primary">取消</Button>
          </>
        )}
      </div>
    </div>
  );
};
